package org.apache.servicecomb.samples.practise.houserush.gateway.dispatcher;

import io.vertx.ext.web.Cookie;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CookieHandler;
import org.apache.servicecomb.edge.core.AbstractEdgeDispatcher;
import org.apache.servicecomb.edge.core.EdgeInvocation;
import org.apache.servicecomb.edge.core.Utils;

import java.util.Map;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/8 20:41
 * @Description:
 */
public class ApiDispatcher extends AbstractEdgeDispatcher {
    @Override
    public int getOrder() {
        //设置Dispatcher的执行顺序
        //返回的数字越小，这个Dispatcher执行优先级就越高
        return 10002;
    }

    @Override
    public void init(Router router) {
        //regex = "/" + this.prefix + "/([^\\\\/]+)/([^\\\\/]+)/(.*)";这个策略用于匹配带版本号的微服务请求
        //regex = "/" + this.prefix + "/([^\\\\/]+)/(.*)";这个策略用于匹配不带版本号的微服务请求

        String regex = "/([^\\\\/]+)/(.*)";


        router.routeWithRegex(regex).handler(CookieHandler.create());
        router.routeWithRegex(regex).handler(this.createBodyHandler());
        router.routeWithRegex(regex).failureHandler(this::onFailure).handler(this::onRequest);
    }

    private void onRequest(RoutingContext context) {
        Map<String, String> pathParams = context.pathParams();
        //获取微服务名字
        String microserviceName = (String) pathParams.get("param0");

        //拼接访问微服务的具体路径
        String path = "/" + pathParams.get("param1");


        EdgeInvocation edgeInvocation = new EdgeInvocation() {
            @Override
            protected void setContext() throws Exception {
                super.setContext();
                //从请求头获取token，或者cookie中获取token，添加到context上下文

                //从请求头中获取token
                String token = context.request().getHeader("Authorization");

                if (token != null) {
                    //如果获取到token，放到context中
                    this.invocation.addContext("Authorization", token);
                } else {
                    //如果没获取到token，尝试从cookie中获取token
                    Cookie cookie = context.getCookie("Authorization");
                    if(cookie != null){
                        //如果获取到，放到context中
                        this.invocation.addContext("Authorization",cookie.getValue());
                    }
                }
                //鉴权之前，需要清空用户id
                context.request().headers().add("customerId","-1");
            }
        };
        edgeInvocation.init(microserviceName, context, path, this.httpServerFilters);
        edgeInvocation.edgeInvoke();
    }
}
